package cn.edu.zzu.demo02Thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {

    private String url ;
    private String fileName ;

    public TestCallable(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    @Override
    public Boolean call() throws Exception {
        DownUtilss.down(url , fileName);
        System.out.println(Thread.currentThread().getName()+"下载了"+fileName);
        return true;
    }

    public static void main(String[] args) throws Exception {
        TestCallable testCallable = new TestCallable("https://gitee.com/zhushangxue/blogimg/raw/master/img/20210804182542.png", "1.png");
        TestCallable testCallable1 = new TestCallable("https://gitee.com/zhushangxue/blogimg/raw/master/img/20210804182542.png", "2.png");
        TestCallable testCallable2 = new TestCallable("https://gitee.com/zhushangxue/blogimg/raw/master/img/20210804182542.png", "3.png");

        //创建执行服务  线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> submit = executorService.submit(testCallable);
        Future<Boolean> submit1 = executorService.submit(testCallable1);
        Future<Boolean> submit2 = executorService.submit(testCallable2);

        //获取结果
        Boolean aBoolean = submit.get();
        Boolean aBoolean1 = submit1.get();
        Boolean aBoolean2 = submit2.get();

        //关闭服务
        executorService.shutdown();

    }
}

class DownUtilss{
    public static void down(String url , String fileName){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(fileName));
        } catch (IOException e) {
            throw new RuntimeException("下载异常");
        }
    }
}